package com.hyk.commonLib.common.utils.gson;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.hyk.commonLib.common.utils.GsonUtils;

import java.lang.reflect.Type;
import java.util.HashMap;

/**
 * Created by 贺玉琨 on 2019/8/19.
 */
public class MultiTypeParser<T> implements JsonDeserializer<T> {
    protected HashMap<String, Class<? extends T>> typeClassMap = new HashMap<>();
    protected Class<? extends T> unexpectedValueClass;
    protected String identifyElementName;

    public MultiTypeParser(String identifyElementName) {
        this.identifyElementName = identifyElementName;
    }

    public MultiTypeParser<T> registerType(String typeElementValue, Class<? extends T> classValue) {
        typeClassMap.put(typeElementValue, classValue);
        return this;
    }

    public MultiTypeParser<T> registerUnexpectedValueType(Class<? extends T> classValue) {
        this.unexpectedValueClass = classValue;
        return this;
    }

    @Override
    public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        String identifyElementValue = json.getAsJsonObject().get(identifyElementName).getAsString();
        Class<?> parseTargetClass = typeClassMap.containsKey(identifyElementValue) ? typeClassMap.get(identifyElementValue) : unexpectedValueClass;
        if (parseTargetClass == null) {
            return null;
        }
        return GsonUtils.getInstance().fromJson(json, (Type) parseTargetClass);
    }
}
